//api.js
var commons = require('commons.js');
// 获取服务端主机地址
const host = commons.getHost();
 
/**
 * 公共微信https请求封装
 * @param url
 * @param type
 * @param data
 * @param callBack
 */

function https(url, type, data, header) {
 // 获取应用实例
 const app = getApp();
  let _loading = false;
  let TOKEN = wx.getStorageSync('token');
  if (!_loading) {
    wx.showLoading({
      title: "加载中" // 数据请求前loading
    });
    _loading = true
  }
  let pro = new Promise((resolve, reject) => {
    wx.request({
      url: host + url,
      method: type,
      data: data,
      header: header ? header : ({
        "Content-Type": "application/json",
        "DTG_MARK": TOKEN
      }),
      success: function (res) {
        // console.log(res)
        let dataCode = res.data.code;
        switch (dataCode) {
          case 200:
            wx.hideLoading();
            return resolve(res);
            break
          case 405:
            wx.hideLoading();
            return resolve(res);
            break
          case 401:
            wx.hideLoading();
            return reject(res)
            break
          case 530:
            wx.hideLoading();
            _loading = false;
            console.log(app.globalData.isShowPrompt);
            if(!app.globalData.isShowPrompt){  //只显示一次提示弹窗
              wx.showModal({
                title: '警告',
                content: res.data.message,
                showCancel: true,
                confirmText: '去登录',
                success: function (res) {
                  // console.log(res);
                  if (res.confirm) {
                    wx.redirectTo({
                      // url: '/pages/user/login/login'
                      url: '/pages/user/login-way/index'
                    })
                  }
                  if (res.cancel) {
                    wx.navigateBack({
                      delta: 1,
                    })
                  }
                }
              })
              app.globalData.isShowPrompt=true;
            }
            return reject(res)
            break
          default:
            wx.hideLoading();
            wx.showToast({
              title: res.data.message || '无数据',
              icon: 'none'
            });
            _loading = false
            return reject(res)
            break
        }

      },
      fail: function (error) {
        reject(error)

      },
    })
  })
  return pro;
}

module.exports = {
  https: https
}